from sqlalchemy import create_engine, Table, MetaData
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


class CenterManager(object):
    def __init__(self, database_path):
        super(CenterManager, self).__init__()
        self.engine = create_engine(f'sqlite:///{database_path}?check_same_thread=False')
        self.Base = declarative_base()
        self.Base.metadata.reflect(self.engine)
        self.metadata = MetaData(self.engine)
        self.session = sessionmaker(bind=self.engine)()

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            orig = super(CenterManager, cls)
            cls._instance = orig.__new__(cls)
        return cls._instance

    def _insert_data(self, recv_list, table_name):
        self.table_obj = Table(table_name, self.metadata,
                               Column('id', Integer, primary_key=True),
                               Column('test_mode', String),
                               Column('wafer_id', String),
                               Column('test_time', String),
                               Column('die_id', String),
                               Column('subdie_id', String),
                               Column('position', String),
                               Column('test_data', String),
                               Column('selected', String))
        self.session.execute(self.table_obj.insert(), recv_list)
        self.session.commit()

    def insert_data(self, recv_list, table_name):
        self._insert_data(recv_list, table_name)


if __name__ == '__main__':
    center_manager = CenterManager("offline.db")
    test_list = []
    for i in range(2):
        for j in range(30):
            test_dict = {"wafer_id": '103{}'.format(i), "die_id": "{}".format(j), "subdie_id": '0',
                         "position": '({},0)'.format(j), "test_mode": "R",
                         "test_data": '{}.{}'.format(1, 2),
                         "test_time": "2022-04-2{} 12:12:32".format(i)}
            test_list.append(test_dict)
    center_manager.insert_data(test_list, 'test')
